/*
 * @Author: szx
 * @Date: 2021-11-02 15:14:08
 * @LastEditTime: 2021-11-02 15:28:38
 * @Description:
 * @FilePath: \leetcode\100-199\116\116.cpp
 */
#include <iostream>
#include <queue>
using namespace std;
class Node {
   public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};

class Solution {
   public:
    Node* connect(Node* root) {
        if (!root) return nullptr;
        if (root->left == nullptr && root->right == nullptr) {
            return root;
        }
        if (root->left) root->left->next = root->right;
        if (root->next) root->right->next = root->next->left;
        connect(root->left);
        connect(root->right);
        return root;
    }
};

class Solution {
   public:
    Node* connect(Node* root) {
        if (root == nullptr) {
            return root;
        }
        queue<Node*> Q;
        Q.push(root);
        while (!Q.empty()) {
            int size = Q.size();
            for (int i = 0; i < size; i++) {
                Node* node = Q.front();
                Q.pop();
                if (i < size - 1) {
                    node->next = Q.front();
                }
                if (node->left != nullptr) {
                    Q.push(node->left);
                }
                if (node->right != nullptr) {
                    Q.push(node->right);
                }
            }
        }
        return root;
    }
};
